import axios from 'axios'
import { ElLoading, ElMessage } from 'element-plus'
import { useUserStore } from '@/stores'
import router from '@/router'

let loadingInstance

const startLoading = () => {
  loadingInstance = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
}

const baseURL = 'http://121.43.148.178:8080'
// const baseURL = 'http://127.0.0.1:8080'

const request = axios.create({
  baseURL,
  timeout: 5000
})

request.interceptors.request.use(
  (config) => {
    startLoading()
    const userStore = useUserStore()
    if (userStore.getToken()) {
      // 请求头添加token
      config.headers.Authorization = userStore.getToken()
    }
    return config
  },
  (err) => {
    loadingInstance.close()
    ElMessage.error('服务器发生错误')
    Promise.reject(err)
  }
)

request.interceptors.response.use(
  (res) => {
    loadingInstance.close()
    if (res.data?.code == '501') {
      router.push('/login')
    }
    return res
  },
  (err) => {
    loadingInstance.close()
    return Promise.reject(err)
  }
)

export default request

export { baseURL }
